<template>
  <div class="data-browser h-full flex flex-col overflow-hidden">
    <!-- 工具栏 -->
    <div class="browser-toolbar flex items-center justify-between p-3 bg-gray-50 border-b border-gray-200">
      <div class="toolbar-left flex items-center space-x-2">
        <span class="text-sm font-medium">
          {{ tab.database }}.{{ tab.table }}
        </span>
        <el-button size="small" @click="handleRefresh" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button size="small" @click="openFilterDialog">
          <el-icon><Filter /></el-icon>
          筛选
        </el-button>
      </div>
      
      <div class="toolbar-right flex items-center space-x-2">
        <el-input
          v-model="searchText"
          placeholder="搜索..."
          size="small"
          style="width: 200px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-dropdown trigger="click" @command="handleExport">
          <el-button size="small">
            <span class="flex items-center">
              <el-icon class="mr-1"><Download /></el-icon>
              导出
              <el-icon class="ml-1"><ArrowDown /></el-icon>
            </span>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="csv">CSV格式</el-dropdown-item>
              <el-dropdown-item command="xlsx">Excel格式</el-dropdown-item>
              <el-dropdown-item command="json">JSON格式</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="browser-content flex-1 overflow-hidden flex flex-col">
      <!-- 加载中状态 -->
      <div v-if="loading" class="executing-state flex-1 flex items-center justify-center">
        <div class="flex items-center">
          <div class="loading-spinner mr-2"></div>
          <span class="text-gray-600">正在加载表数据...</span>
        </div>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-result p-4 flex-1">
        <el-alert
          :title="error"
          type="error"
          :closable="false"
          show-icon
        />
      </div>

      <!-- 数据表格 -->
      <div v-else class="data-table flex-1 overflow-hidden flex flex-col">
        <!-- 使用新的DatabaseTable组件 -->
        <div class="flex-1 relative">
        <database-table
          v-if="tableColumns.length > 0"
          ref="databaseTable"
          :data="tableData"
          :columns="tableColumns"
          :primary-keys="primaryKeys"
          :read-only-columns="readOnlyColumns"
          :editable="true"
          :show-toolbar="true"
          :show-status-bar="true"
          :current-page="currentPage"
          :page-size="pageSize"
          :loading="loading"
          @save="handleSaveChanges"
          @change="handleCellChange"
          @select="handleCellSelect"
          @column-resize="handleColumnResize"
          @row-resize="handleRowResize"
          @sort="handleSort"
          @delete-rows="handleDeleteRows"
          class="flex-1"
        />
          
          <!-- 分页加载遮罩 -->
          <div v-if="paginating" class="absolute inset-0 bg-white bg-opacity-75 flex items-center justify-center z-10">
            <div class="flex items-center">
              <div class="loading-spinner mr-2"></div>
              <span class="text-gray-600">正在加载...</span>
            </div>
          </div>
          
          <!-- 排序加载效果 -->
          <div v-if="sorting" class="sort-progress">
            <div class="sort-progress-bar"></div>
          </div>
        </div>
        
        <!-- 等待列信息加载 -->
        <div v-if="tableColumns.length === 0 && !loading" class="flex-1 flex items-center justify-center">
          <div class="text-gray-600">正在加载表结构...</div>
        </div>

        <!-- 分页控制 -->
        <div class="pagination-container border-t border-gray-200 py-2 px-4 flex justify-between items-center">
          <div class="text-sm text-gray-600">
            共 {{ totalRows }} 行数据
          </div>
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="sizes, prev, pager, next, jumper"
            :total="totalRows"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            size="small"
          />
        </div>
      </div>
    </div>

    <!-- 筛选对话框 -->
    <el-dialog
      v-model="filterDialogVisible"
      title="数据筛选"
      width="600px"
    >
      <div class="filter-form">
        <el-form>
          <el-form-item v-for="(filter, index) in filters" :key="index" class="mb-4">
            <div class="flex items-center space-x-2">
              <el-select v-model="filter.column" placeholder="选择列" class="w-1/3">
                <el-option
                  v-for="col in tableColumns"
                  :key="col.field"
                  :label="col.title"
                  :value="col.field"
                />
              </el-select>
              <el-select v-model="filter.operator" placeholder="操作符" class="w-1/4">
                <el-option label="等于" value="=" />
                <el-option label="不等于" value="!=" />
                <el-option label="大于" value=">" />
                <el-option label="大于等于" value=">=" />
                <el-option label="小于" value="<" />
                <el-option label="小于等于" value="<=" />
                <el-option label="包含" value="LIKE" />
                <el-option label="不包含" value="NOT LIKE" />
                <el-option label="为空" value="IS NULL" />
                <el-option label="不为空" value="IS NOT NULL" />
              </el-select>
              <el-input v-model="filter.value" placeholder="值" class="w-1/3" />
              <el-button type="danger" icon="Delete" @click="removeFilter(index)" />
            </div>
          </el-form-item>
          <el-button type="primary" @click="addFilter" class="mt-2">
            <el-icon><Plus /></el-icon>
            添加条件
          </el-button>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetFilters">重置</el-button>
          <el-button type="primary" @click="applyFilters">
            应用筛选
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, ArrowDown, Plus, Filter, Delete, Refresh, Search } from '@element-plus/icons-vue'
import { DatabaseService } from '../../services/database.js'
import DatabaseTable from '../common/DatabaseTable.vue'

const props = defineProps({
  tab: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update', 'column-resize', 'row-resize'])

// 状态管理
const loading = ref(false)
const paginating = ref(false)  // 新增：分页加载状态
const sorting = ref(false)  // 新增：排序加载状态
const error = ref(null)
const searchText = ref('')
const tableData = ref([])
const tableColumns = ref([])
const primaryKeys = ref([])
const readOnlyColumns = ref([])
const totalRows = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const filterDialogVisible = ref(false)
const filters = ref([])

// 排序状态
const sortColumn = ref(null)
const sortDirection = ref(null)

// 组件引用
const databaseTable = ref(null)

// 防抖定时器
let sortDebounceTimer = null

// 生命周期钩子
onMounted(async () => {
  // 从 localStorage 恢复排序状态
  const database = props.tab.database || props.tab.data?.database
  const table = props.tab.table || props.tab.data?.table
  if (database && table) {
    const sortKey = `table-sort-${database}-${table}`
    const savedSort = localStorage.getItem(sortKey)
    if (savedSort) {
      try {
        const { column, direction } = JSON.parse(savedSort)
        sortColumn.value = column
        sortDirection.value = direction
      } catch (e) {
        console.error('恢复排序状态失败:', e)
      }
    }
  }
  
  // 先获取表元数据，然后获取数据
  await fetchTableMetadata()
  await fetchTableData()
})

// 获取表元数据
const fetchTableMetadata = async () => {
  try {
    // 获取表和数据库名称
    const database = props.tab.database || props.tab.data?.database
    const table = props.tab.table || props.tab.data?.table
    
    // 确保数据库名和表名存在
    if (!database || !table) {
      throw new Error('数据库名或表名缺失')
    }
    
    // 获取表列信息
    const columnData = await DatabaseService.getTableColumns(
      props.tab.connectionId,
      database,
      table
    )
    
    // 生成列配置
    tableColumns.value = columnData.map(col => {
      // 根据列类型和名称智能设置宽度
      let width = 150
      const colType = (col.Type || col.type || '').toLowerCase()
      const colName = (col.Name || col.name || '').toLowerCase()
      
      // 根据数据类型设置宽度
      if (colType.includes('int') || colType.includes('tinyint') || colType.includes('smallint')) {
        width = 100
      } else if (colType.includes('bigint')) {
        width = 120
      } else if (colType.includes('decimal') || colType.includes('float') || colType.includes('double')) {
        width = 120
      } else if (colType.includes('date') && !colType.includes('datetime')) {
        width = 110
      } else if (colType.includes('datetime') || colType.includes('timestamp')) {
        width = 180
      } else if (colType.includes('text') || colType.includes('blob')) {
        width = 300
      } else if (colType.includes('varchar')) {
        const match = colType.match(/varchar\((\d+)\)/)
        if (match) {
          const maxLength = parseInt(match[1])
          width = Math.min(Math.max(100, maxLength * 8), 400)
        }
      }
      
      // 根据列名调整（ID列通常较窄）
      if (colName === 'id' || colName.endsWith('_id')) {
        width = Math.min(width, 80)
      } else if (colName.includes('name') || colName.includes('title')) {
        width = Math.max(width, 200)
      } else if (colName.includes('description') || colName.includes('content')) {
        width = Math.max(width, 300)
      } else if (colName === 'status' || colName === 'type') {
        width = Math.min(width, 100)
      }
      
      // 根据数据类型自动设置编辑器类型
      let editType = 'text'
      let editOptions = {}
      
      // 数字类型
      if (colType.includes('int') || colType.includes('decimal') || colType.includes('float') || colType.includes('double')) {
        editType = 'number'
        editOptions = {
          step: colType.includes('int') ? 1 : 0.01,
          precision: colType.includes('decimal') || colType.includes('float') || colType.includes('double') ? 2 : 0
        }
      }
      // 日期时间类型
      else if (colType === 'time' || (colType.includes('time') && !colType.includes('datetime') && !colType.includes('timestamp'))) {
        editType = 'time'
      }
      else if (colType === 'date' || (colType.includes('date') && !colType.includes('datetime'))) {
        editType = 'date'
      }
      else if (colType.includes('datetime') || colType.includes('timestamp')) {
        editType = 'datetime'
      }
      // 布尔类型
      else if (colType.includes('bool') || colType.includes('bit') || colType === 'tinyint(1)') {
        editType = 'checkbox'
      }
      // 大文本类型
      else if (colType.includes('text') || colType.includes('json')) {
        editType = 'textarea'
        editOptions = {
          rows: 4
        }
      }
      // 邮箱类型（根据列名推断）
      else if (colName.includes('email') || colName.includes('mail')) {
        editType = 'email'
        editOptions = {
          placeholder: 'user@example.com'
        }
      }
      // URL类型（根据列名推断）
      else if (colName.includes('url') || colName.includes('link') || colName.includes('website')) {
        editType = 'url'
        editOptions = {
          placeholder: 'https://example.com'
        }
      }
      // 颜色类型（根据列名推断）
      else if (colName.includes('color') || colName.includes('colour')) {
        editType = 'color'
      }
      // 状态类型（可能使用下拉选择）
      else if (colName === 'status' || colName === 'state' || colName === 'type') {
        // 暂时使用文本编辑器，后续可以根据实际值动态生成选项
        editType = 'text'
      }
      
      // 如果是长文本，设置最大长度
      if (colType.includes('varchar')) {
        const match = colType.match(/varchar\((\d+)\)/)
        if (match) {
          editOptions.maxLength = parseInt(match[1])
        }
      }
      
      return {
        field: col.Name || col.name,
        title: col.Name || col.name,
        type: colType,
        width: width,
        isPrimaryKey: col.IsPrimaryKey || col.isPrimaryKey || false,
        isNullable: col.IsNullable || col.isNullable || true,
        defaultValue: col.Default || col.defaultValue || null,
        editType: editType,
        editOptions: editOptions,
        sortable: true  // 默认所有列都可排序
      }
    })
    
    // 提取主键列
    primaryKeys.value = tableColumns.value
      .filter(col => col.isPrimaryKey)
      .map(col => col.field)
    
    // 如果没有找到主键，尝试从原始数据再次查找（不同数据库系统可能有不同的属性名）
    if (primaryKeys.value.length === 0) {
      primaryKeys.value = columnData
        .filter(col => 
          col.IsPrimaryKey === true || 
          col.isPrimaryKey === true || 
          col.Key === 'PRI' ||
          col.is_primary_key === true ||
          col.keytype === 'PRIMARY KEY'
        )
        .map(col => col.Name || col.name || col.field)
    }
    
    console.log('检测到主键列:', primaryKeys.value)
    
    // 设置只读列（例如自增列）
    readOnlyColumns.value = columnData
      .filter(col => col.Extra === 'auto_increment' || col.IsIdentity)
      .map(col => col.Name || col.name)
    
  } catch (err) {
    error.value = `获取表结构失败: ${err.message || err}`
    ElMessage.error(`获取表结构失败: ${err.message || err}`)
  }
}

// 获取表数据
const fetchTableData = async (operationType = 'load') => {
  // 根据操作类型决定使用哪个加载状态
  if (operationType === 'paginate') {
    paginating.value = true
  } else if (operationType === 'sort') {
    sorting.value = true
  } else {
  loading.value = true
  }
  error.value = null
  
  try {
    // 获取表和数据库名称
    const database = props.tab.database || props.tab.data?.database
    const table = props.tab.table || props.tab.data?.table
    
    // 确保数据库名和表名存在
    if (!database || !table) {
      throw new Error('数据库名或表名缺失')
    }
    
    // 如果列信息不存在，先获取列信息
    if (tableColumns.value.length === 0) {
      await fetchTableMetadata()
    }
    
    // 构建查询SQL
    let sql = `SELECT * FROM ${database}.${table}`
    
    // 添加筛选条件
    if (filters.value.length > 0) {
      const whereConditions = filters.value
        .filter(f => f.column && f.operator)
        .map(f => {
          if (['IS NULL', 'IS NOT NULL'].includes(f.operator)) {
            return `${f.column} ${f.operator}`
          } else if (['LIKE', 'NOT LIKE'].includes(f.operator)) {
            return `${f.column} ${f.operator} '%${f.value}%'`
          } else {
            return `${f.column} ${f.operator} '${f.value}'`
          }
        })
      
      if (whereConditions.length > 0) {
        sql += ` WHERE ${whereConditions.join(' AND ')}`
      }
    }
    
    // 添加搜索文本
    if (searchText.value.trim()) {
      const searchConditions = tableColumns.value
        .filter(col => ['varchar', 'text', 'char', 'nvarchar', 'ntext'].includes(col.type))
        .map(col => `${col.field} LIKE '%${searchText.value.trim()}%'`)
      
      if (searchConditions.length > 0) {
        sql += sql.includes('WHERE') ? ` AND (${searchConditions.join(' OR ')})` : ` WHERE ${searchConditions.join(' OR ')}`
      }
    }
    
    // 添加排序
    if (sortColumn.value && sortDirection.value) {
      sql += ` ORDER BY ${sortColumn.value} ${sortDirection.value.toUpperCase()}`
    }
    
    // 添加分页
    sql += ` LIMIT ${pageSize.value} OFFSET ${(currentPage.value - 1) * pageSize.value}`
    
    // 执行查询
    const queryResult = await DatabaseService.executeQuery(
      props.tab.connectionId,
      sql
    )
    
    // 验证查询结果格式
    if (!queryResult.rows || !Array.isArray(queryResult.rows)) {
      console.error("Invalid query result format:", queryResult)
      throw new Error("查询结果格式无效")
    }
    
    tableData.value = queryResult.rows
    
    // 获取总行数
    let countSql = `SELECT COUNT(*) as total FROM ${database}.${table}`
    
    // 构建 WHERE 子句（与主查询相同，但不包含排序和分页）
    let whereClause = ''
    
    // 添加筛选条件
    if (filters.value.length > 0) {
      const whereConditions = filters.value
        .filter(f => f.column && f.operator)
        .map(f => {
          if (['IS NULL', 'IS NOT NULL'].includes(f.operator)) {
            return `${f.column} ${f.operator}`
          } else if (['LIKE', 'NOT LIKE'].includes(f.operator)) {
            return `${f.column} ${f.operator} '%${f.value}%'`
          } else {
            return `${f.column} ${f.operator} '${f.value}'`
          }
        })
      
      if (whereConditions.length > 0) {
        whereClause = whereConditions.join(' AND ')
      }
    }
    
    // 添加搜索条件
    if (searchText.value.trim()) {
      const searchConditions = tableColumns.value
        .filter(col => col.type && ['varchar', 'text', 'char', 'nvarchar', 'ntext'].includes(col.type))
        .map(col => `${col.field} LIKE '%${searchText.value.trim()}%'`)
      
      if (searchConditions.length > 0) {
        const searchClause = `(${searchConditions.join(' OR ')})`
        whereClause = whereClause ? `${whereClause} AND ${searchClause}` : searchClause
      }
    }
    
    // 将 WHERE 子句添加到 COUNT 查询
    if (whereClause) {
      countSql += ` WHERE ${whereClause}`
    }
    
    const countResult = await DatabaseService.executeQuery(
      props.tab.connectionId,
      countSql
    )
    
    if (countResult.Error) {
      throw new Error(countResult.Error)
    }
    
    totalRows.value = countResult.rows?.[0]?.total || 0
    
    // 数据加载成功后，恢复排序显示
    if (sortColumn.value && sortDirection.value) {
      nextTick(() => {
        const canvasTable = databaseTable.value?.getTable?.()
        if (canvasTable?.setSortConfig) {
          canvasTable.setSortConfig(sortColumn.value, sortDirection.value)
        }
      })
    }
    
  } catch (err) {
    error.value = `加载表数据失败: ${err.message || err}`
    ElMessage.error(`加载表数据失败: ${err.message || err}`)
    tableData.value = []
    console.error("Error in fetchTableData:", err)
  } finally {
    loading.value = false
    paginating.value = false
    sorting.value = false
    
    // 数据加载完成后，恢复保存的行高设置
    nextTick(() => {
      if (databaseTable.value) {
        const table = databaseTable.value.getTable?.()
        if (table) {
          // 恢复行高设置
          if (table.eventManager) {
            const rowHeights = JSON.parse(localStorage.getItem('table-row-heights') || '{}')
            const tableId = `${props.tab.database || props.tab.data?.database}_${props.tab.table || props.tab.data?.table}`
            const savedHeights = rowHeights[tableId] || {}
            
            Object.entries(savedHeights).forEach(([row, height]) => {
              table.eventManager.setRowHeight(parseInt(row), height)
            })
          }
        }
      }
    })
  }
}

// 处理保存更改
const handleSaveChanges = async (changes) => {
  try {
    loading.value = true
    
    const database = props.tab.database || props.tab.data?.database
    const table = props.tab.table || props.tab.data?.table
    
    // 处理修改的数据
    for (const change of changes.modified) {
      const { row, field, newValue, oldValue } = change
      
      // 构建更新SQL
      const rowData = tableData.value[row]
      
      // 检查rowData是否存在，如果不存在则跳过
      if (!rowData) {
        console.warn(`尝试更新的行 ${row} 数据不存在，跳过此更改`)
        continue
      }
      
      // 特殊情况：如果这是一个ID字段的更新，且之前为null，可能是新行需要处理为插入
      if (field === 'id' && (oldValue === null || oldValue === undefined)) {
        console.warn(`检测到ID字段更新，可能是新行。当前值: ${newValue}, 旧值: ${oldValue}`)
        
        // 收集所有字段数据创建一个完整的行对象用于插入
        const insertRow = { ...rowData }
        insertRow[field] = newValue // 更新当前修改的字段
        
        // 移除前端使用的特殊属性
        if (insertRow._isNew) delete insertRow._isNew
        if (insertRow._rowNumber) delete insertRow._rowNumber
        
        // 将此行添加到inserted数组中，以便后续处理
        if (!changes.inserted) changes.inserted = []
        changes.inserted.push(insertRow)
        
        // 跳过当前的更新操作
        continue
      }
      
      // 检查行是否是新插入的行，由前端标记
      if (rowData._isNew === true) {
        console.warn(`行 ${row} 是新插入的行，需要先插入才能更新。将自动处理为插入操作`)
        
        // 收集所有字段数据创建一个完整的行对象用于插入
        const insertRow = { ...rowData }
        insertRow[field] = newValue // 更新当前修改的字段
        
        // 移除前端使用的特殊属性
        delete insertRow._isNew
        delete insertRow._rowNumber
        
        // 将此行添加到inserted数组中，以便后续处理
        if (!changes.inserted) changes.inserted = []
        changes.inserted.push(insertRow)
        
        // 跳过当前的更新操作
        continue
      }
      
      // 检查主键是否存在
      if (!primaryKeys.value || primaryKeys.value.length === 0) {
        throw new Error('无法更新数据：该表没有主键')
      }
      
      // 检查每个主键在rowData中是否都有值
      let missingPrimaryKey = false
      const whereConditions = primaryKeys.value
        .map(pk => {
          // 如果主键值不存在，标记为缺失
          if (rowData[pk] === undefined || rowData[pk] === null) {
            missingPrimaryKey = true
            return null
          }
          return `${pk}='${rowData[pk]}'`
        })
        .filter(Boolean) // 过滤掉null值
        .join(' AND ')
      
      if (missingPrimaryKey || !whereConditions) {
        throw new Error(`无法更新数据：行 ${row} 缺少主键值`)
      }
      
      // 构建更新值
      let setValue = ''
      if (newValue === null || newValue === undefined) {
        setValue = 'NULL'
      } else if (typeof newValue === 'string') {
        // 检测是否为日期格式，例如 '2025-06-21 05:57:00'
        const datePattern = /^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$/
        if (datePattern.test(newValue)) {
          // 已经是MySQL兼容的日期格式，直接使用
          setValue = `'${newValue}'`
        } else if (newValue.includes('GMT') || newValue.match(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/)) {
          // 尝试转换为标准日期格式
          try {
            const dateObj = new Date(newValue)
            if (!isNaN(dateObj.getTime())) {
              const year = dateObj.getFullYear()
              const month = String(dateObj.getMonth() + 1).padStart(2, '0')
              const day = String(dateObj.getDate()).padStart(2, '0')
              const hours = String(dateObj.getHours()).padStart(2, '0')
              const minutes = String(dateObj.getMinutes()).padStart(2, '0')
              const seconds = String(dateObj.getSeconds()).padStart(2, '0')
              setValue = `'${year}-${month}-${day} ${hours}:${minutes}:${seconds}'`
            } else {
              setValue = `'${newValue.replace(/'/g, "''")}'`
            }
          } catch (e) {
            // 如果日期解析失败，按普通字符串处理
            setValue = `'${newValue.replace(/'/g, "''")}'`
          }
        } else {
          // 普通字符串处理
          setValue = `'${newValue.replace(/'/g, "''")}'`
        }
      } else {
        setValue = newValue
      }
      
      const sql = `UPDATE ${database}.${table} SET ${field}=${setValue} WHERE ${whereConditions}`
      console.log('Executing update SQL:', sql)
      
      // 执行更新
      const result = await DatabaseService.executeQuery(props.tab.connectionId, sql)
      
      if (result.Error || result.error) {
        throw new Error(result.Error || result.error || '更新失败')
      }
    }
    
    // 处理新增的数据 - 移到删除之前处理，确保索引正确
    for (const newRow of changes.inserted) {
      // 从newRow中提取实际的数据
      const rowData = newRow.data || newRow
      const columns = Object.keys(rowData).filter(key => key !== '_rowNumber' && key !== '_isNew')
      const values = columns.map(col => {
        const value = rowData[col]
        
        // 值为null或undefined时返回NULL
        if (value === null || value === undefined) return 'NULL'
        
        // 处理日期类型（Date或日期字符串）
        if (value instanceof Date || (typeof value === 'string' && value.includes('GMT'))) {
          // 尝试转换为日期对象
          let dateValue
          try {
            dateValue = value instanceof Date ? value : new Date(value)
            // 检查是否为有效日期
            if (!isNaN(dateValue.getTime())) {
              // 格式化为MySQL兼容的日期格式: YYYY-MM-DD HH:MM:SS
              const year = dateValue.getFullYear()
              const month = String(dateValue.getMonth() + 1).padStart(2, '0')
              const day = String(dateValue.getDate()).padStart(2, '0')
              const hours = String(dateValue.getHours()).padStart(2, '0')
              const minutes = String(dateValue.getMinutes()).padStart(2, '0')
              const seconds = String(dateValue.getSeconds()).padStart(2, '0')
              return `'${year}-${month}-${day} ${hours}:${minutes}:${seconds}'`
            }
          } catch (e) {
            console.warn(`日期转换失败: ${e.message}`, value)
          }
        }
        
        // 处理字符串值（添加引号并转义单引号）
        if (typeof value === 'string') return `'${value.replace(/'/g, "''")}'`
        
        // 其他类型原样返回
        return value
      })
      
      const sql = `INSERT INTO ${database}.${table} (${columns.join(', ')}) VALUES (${values.join(', ')})`
      console.log('Executing insert SQL:', sql)
      
      const result = await DatabaseService.executeQuery(props.tab.connectionId, sql)
      
      if (result.Error || result.error) {
        throw new Error(result.Error || result.error || '插入失败')
      }
    }
    
    // 处理删除的数据
    for (const deletedItem of changes.deleted) {
      // 获取索引和行数据（兼容两种格式：直接是索引或是{index, data}对象）
      const rowIndex = typeof deletedItem === 'object' ? deletedItem.index : deletedItem
      const rowData = typeof deletedItem === 'object' ? deletedItem.data : tableData.value[rowIndex]
      
      // 检查rowData是否存在，如果不存在则跳过
      if (!rowData) {
        console.warn(`尝试删除的行 ${rowIndex} 数据不存在，跳过此操作`)
        continue
      }
      
      // 检查主键是否存在
      if (!primaryKeys.value || primaryKeys.value.length === 0) {
        throw new Error('无法删除数据：该表没有主键')
      }
      
      // 检查每个主键在rowData中是否都有值
      let missingPrimaryKey = false
      const whereConditions = primaryKeys.value
        .map(pk => {
          // 如果主键值不存在，标记为缺失
          if (rowData[pk] === undefined || rowData[pk] === null) {
            missingPrimaryKey = true
            return null
          }
          return `${pk}='${rowData[pk]}'`
        })
        .filter(Boolean) // 过滤掉null值
        .join(' AND ')
      
      if (missingPrimaryKey || !whereConditions) {
        throw new Error(`无法删除数据：行 ${rowIndex} 缺少主键值`)
      }
      
      const sql = `DELETE FROM ${database}.${table} WHERE ${whereConditions}`
      console.log('Executing delete SQL:', sql)
      
      const result = await DatabaseService.executeQuery(props.tab.connectionId, sql)
      
      if (result.Error || result.error) {
        throw new Error(result.Error || result.error || '删除失败')
      }
    }
    
    ElMessage.success('数据已保存')
    
    // 调用 CanvasTable 的 commit 方法，清除更改状态
    const canvasTable = databaseTable.value?.getTable?.()
    if (canvasTable) {
      canvasTable.commit()
    }
    
    // 只有在所有操作都成功后才刷新数据
    // 这样可以避免新增行在保存过程中消失
    await fetchTableData()
    
  } catch (err) {
    console.error('Save error:', err)
    ElMessage.error(`保存失败: ${err.message || err}`)
  } finally {
    loading.value = false
  }
}

// 处理单元格变化
const handleCellChange = (change) => {
  // Cell change handled
}

// 处理单元格选择
const handleCellSelect = (selection) => {
  // Cell selection handled
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  
  // 延迟加载确保DOM更新完成
  nextTick(() => {
    fetchTableData('paginate')  // 使用 'paginate' 操作类型
  })
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  
  // 延迟加载确保DOM更新完成
  nextTick(() => {
    fetchTableData('paginate')  // 使用 'paginate' 操作类型
  })
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchTableData('paginate')  // 使用分页加载状态
}

// 筛选条件管理
const openFilterDialog = () => {
  filterDialogVisible.value = true
  if (filters.value.length === 0) {
    addFilter()
  }
}

const addFilter = () => {
  filters.value.push({
    column: tableColumns.value.length > 0 ? tableColumns.value[0].field : '',
    operator: '=',
    value: ''
  })
}

const removeFilter = (index) => {
  filters.value.splice(index, 1)
}

const resetFilters = () => {
  filters.value = []
  addFilter()
}

const applyFilters = () => {
  currentPage.value = 1
  filterDialogVisible.value = false
  fetchTableData('paginate')  // 使用分页加载状态
}

// 导出处理
const handleExport = async (format) => {
  try {
    loading.value = true
    
    const database = props.tab.database || props.tab.data?.database
    const table = props.tab.table || props.tab.data?.table
    
    // 构建导出查询SQL（不分页，但保留筛选条件）
    let sql = `SELECT * FROM ${database}.${table}`
    
    // 添加筛选条件
    if (filters.value.length > 0) {
      const whereConditions = filters.value
        .filter(f => f.column && f.operator)
        .map(f => {
          if (['IS NULL', 'IS NOT NULL'].includes(f.operator)) {
            return `${f.column} ${f.operator}`
          } else if (['LIKE', 'NOT LIKE'].includes(f.operator)) {
            return `${f.column} ${f.operator} '%${f.value}%'`
          } else {
            return `${f.column} ${f.operator} '${f.value}'`
          }
        })
      
      if (whereConditions.length > 0) {
        sql += ` WHERE ${whereConditions.join(' AND ')}`
      }
    }
    
    // 添加搜索文本
    if (searchText.value.trim()) {
      const searchConditions = tableColumns.value
        .filter(col => ['varchar', 'text', 'char', 'nvarchar', 'ntext'].includes(col.type))
        .map(col => `${col.field} LIKE '%${searchText.value.trim()}%'`)
      
      if (searchConditions.length > 0) {
        sql += sql.includes('WHERE') ? ` AND (${searchConditions.join(' OR ')})` : ` WHERE ${searchConditions.join(' OR ')}`
      }
    }
    
    // 添加排序（导出时也保持排序）
    if (sortColumn.value && sortDirection.value) {
      sql += ` ORDER BY ${sortColumn.value} ${sortDirection.value.toUpperCase()}`
    }
    
    // 执行查询获取所有匹配数据
    const queryResult = await DatabaseService.executeQuery(
      props.tab.connectionId,
      sql
    )
    
    if (queryResult.Error) {
      throw new Error(queryResult.Error)
    }
    
    const exportData = queryResult.rows || []
    
    if (exportData.length === 0) {
      ElMessage.warning('没有可导出的数据')
      return
    }
    
    // 根据格式导出
    switch (format) {
      case 'csv':
        exportCSV(exportData)
        break
      case 'xlsx':
        ElMessage.info('Excel导出功能开发中...')
        break
      case 'json':
        exportJSON(exportData)
        break
    }
  } catch (err) {
    ElMessage.error(`导出失败: ${err.message || err}`)
  } finally {
    loading.value = false
  }
}

// 导出CSV
const exportCSV = (data) => {
  const headers = tableColumns.value.map(col => col.field)
  
  // 创建CSV内容
  const csvContent = [
    headers.join(','),
    ...data.map(row => headers.map(header => {
      const value = row[header]
      if (value === null || value === undefined) return ''
      return typeof value === 'string' ? `"${value.replace(/"/g, '""')}"` : value
    }).join(','))
  ].join('\n')
  
  // 创建下载链接
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', `${props.tab.database}.${props.tab.table}_export.csv`)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('CSV导出成功')
}

// 导出JSON
const exportJSON = (data) => {
  const jsonContent = JSON.stringify(data, null, 2)
  
  // 创建下载链接
  const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', `${props.tab.database}.${props.tab.table}_export.json`)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('JSON导出成功')
}

// 刷新处理
const handleRefresh = () => {
  // 确保在UI更新后再获取数据
  nextTick(() => {
    // 直接刷新数据，无需确认
    fetchTableData()
  })
}

// 处理列宽调整
const handleColumnResize = (event) => {
  emit('column-resize', event)
  
  // 可以在这里保存列宽设置到本地存储
  const columnWidths = JSON.parse(localStorage.getItem('table-column-widths') || '{}')
  const tableId = `${props.tab.database}_${props.tab.table}` // 使用数据库和表名作为唯一标识
  if (!columnWidths[tableId]) columnWidths[tableId] = {}
  
  // 确保 event.column 是列索引
  if (typeof event.column === 'number' && tableColumns.value[event.column]) {
    const columnField = tableColumns.value[event.column].field
    columnWidths[tableId][columnField] = event.width
    localStorage.setItem('table-column-widths', JSON.stringify(columnWidths))
  }
}

// 处理行高调整
const handleRowResize = (event) => {
  emit('row-resize', event)
  
  // 可以在这里保存行高设置
  const rowHeights = JSON.parse(localStorage.getItem('table-row-heights') || '{}')
  const tableId = `${props.tab.database}_${props.tab.table}`
  if (!rowHeights[tableId]) rowHeights[tableId] = {}
  rowHeights[tableId][event.row] = event.height
  localStorage.setItem('table-row-heights', JSON.stringify(rowHeights))
}

// 处理排序
const handleSort = (event) => {
  // 防抖处理，避免重复触发
  if (sortDebounceTimer) {
    clearTimeout(sortDebounceTimer)
  }
  
  sortDebounceTimer = setTimeout(() => {
    // 更新排序状态
    sortColumn.value = event.direction ? event.column : null
    sortDirection.value = event.direction
    
    // 保存排序状态到 localStorage
    const database = props.tab.database || props.tab.data?.database
    const table = props.tab.table || props.tab.data?.table
    if (database && table) {
      const sortKey = `table-sort-${database}-${table}`
      if (sortColumn.value && sortDirection.value) {
        localStorage.setItem(sortKey, JSON.stringify({
          column: sortColumn.value,
          direction: sortDirection.value
        }))
      } else {
        localStorage.removeItem(sortKey)
      }
    }
    
    // 重置到第一页
    currentPage.value = 1
    
    // 重新获取数据
    fetchTableData('sort')
  }, 300)
}

// 处理立即删除行
const handleDeleteRows = async (rowsToDelete) => {
  try {
    loading.value = true
    
    const database = props.tab.database || props.tab.data?.database
    const table = props.tab.table || props.tab.data?.table
    
    // 逐个处理删除行
    for (const {index, data: rowData} of rowsToDelete) {
      // 检查主键是否存在
      if (!primaryKeys.value || primaryKeys.value.length === 0) {
        throw new Error('无法删除数据：该表没有主键')
      }
      
      // 检查每个主键在rowData中是否都有值
      let missingPrimaryKey = false
      const whereConditions = primaryKeys.value
        .map(pk => {
          // 如果主键值不存在，标记为缺失
          if (rowData[pk] === undefined || rowData[pk] === null) {
            missingPrimaryKey = true
            return null
          }
          return `${pk}='${rowData[pk]}'`
        })
        .filter(Boolean) // 过滤掉null值
        .join(' AND ')
      
      if (missingPrimaryKey || !whereConditions) {
        throw new Error(`无法删除数据：行 ${index} 缺少主键值`)
      }
      
      const sql = `DELETE FROM ${database}.${table} WHERE ${whereConditions}`
      console.log('立即执行删除SQL:', sql)
      
      const result = await DatabaseService.executeQuery(props.tab.connectionId, sql)
      
      if (result.Error || result.error) {
        throw new Error(result.Error || result.error || '删除失败')
      }
    }
    
    // 删除成功后，调用 commit 方法处理表格状态
    const canvasTable = databaseTable.value?.getTable?.()
    if (canvasTable) {
      canvasTable.commit()
    }
    
    // 删除成功后刷新表格数据，确保与数据库同步
    await fetchTableData()
    
    ElMessage.success(`成功删除 ${rowsToDelete.length} 行数据`)
    
  } catch (err) {
    console.error('删除错误:', err)
    ElMessage.error(`删除失败: ${err.message || err}`)
    
    // 删除失败时回滚表格状态
    const canvasTable = databaseTable.value?.getTable?.()
    if (canvasTable) {
      canvasTable.rollback()
    }
    
    // 刷新表格确保与数据库一致
    await fetchTableData()
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.data-browser {
  background: #ffffff;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #e5e7eb;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 添加排序进度条动画 */
.sort-progress {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  z-index: 20;
  overflow: hidden;
}

.sort-progress-bar {
  height: 100%;
  background: linear-gradient(90deg, transparent, #3b82f6, transparent);
  animation: sortProgress 1.5s ease-in-out infinite;
}

@keyframes sortProgress {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}
</style> 